<template>
  <el-form
    size="large"
    :rules="FORM_RULES"
    ref="formRef"
    :model="formData"
    label-width="180px"
    class="form-data"
    scroll-to-error
  >
    <div class="form-data-title">问卷维护</div>
    <el-form-item prop="bt" label="标题">
      <el-input clearable placeholder="请输入标题" v-model="formData.bt"></el-input>
    </el-form-item>
    <el-form-item prop="mark" label="模板">
      <el-input clearable placeholder="请输入模板" v-model="formData.mark"></el-input>
    </el-form-item>
    <el-form-item prop="num" label="抽取数量">
      <el-input-number v-model="formData.num" :step="5" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item prop="year" label="调查年份">
      <el-date-picker
          v-model="formData.year"
          type="year"
          placeholder="请选择调查年份"
          value-format="YYYY"
        />
    </el-form-item>
    <el-form-item prop="entryDate" label="生效日期">
      <el-date-picker
        v-model="formData.entryDate"
        type="daterange"
        unlink-panels
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="max-width: 600px"
      />
    </el-form-item>

    <div class="form-sub-title">单位指标维护</div>
    <div v-for="(domain, index) in formData.questions" style="width:100%;padding:20px 0 ;border-top: 1px solid var(--el-border-color)"
          :key="domain.id">
      <el-row>
      <el-col :span="1" class="sub-order">
        <span>{{index+1}}</span>
      </el-col>
      <el-col :span="19">
        <el-form-item
          label="维护单位"
          :prop="'questions.' + index + '.orgName'"
          :rules="{
            required: true,
            message: '请选择维护单位',
            trigger: 'change',
          }"
        >
          <el-input clearable placeholder="请选择维护单位" v-model="domain.orgName" @click="handleClickOrg(item,index)" readonly>
            <template #append>
              <el-button type="primary" @click="handleClickOrg(item,index)">选择</el-button>
            </template>
          </el-input>

          <!-- <el-select v-model="domain.orgId" filterable placeholder="请选择" style="width: 300px">
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.orgName"
              :value="dept.id"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item
          label="指标"
          :prop="'questions.' + index + '.question'"
          :rules="{
            required: true,
            message: '请维护调查指标',
            trigger: 'change',
          }"
        >
          <el-input clearable placeholder="请维护指标" v-model="domain.question"></el-input>
        </el-form-item>
        <el-form-item
          label="排序"
          :prop="'questions.' + index + '.showOrder'"
          :rules="{
            required: true,
            message: '请维护排序',
            trigger: 'change',
          }"
        >
          <el-input-number v-model="domain.showOrder" :step="2"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="2">
         <el-button type="primary" size="large" @click="addItem" v-if="index+1 === formData.questions.length">新增</el-button>
         <el-popconfirm :title="showContent" @confirm="delItem(domain,index)" v-if="formData.questions.length>1">
            <template #reference>
              <el-button type="warning" size="large" style="margin-left:0">删除</el-button>
            </template>
          </el-popconfirm>
      </el-col>
    </el-row>
    </div>

    <div class="form-footer">
      <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
      <el-button type="primary" @click="onConfirmInitDept">初始化部门</el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </div>
  </el-form>

  <el-dialog v-model="dialogFormVisible" :show-close="false" class="orgDialog" :width="600">
    <el-input clearable placeholder="请输入" v-model="searchOrg"></el-input>
    <el-scrollbar height="400px">
      <ul>
        <li :class="selectedOrg(item)" v-for="item in selectDepts" :key="item.orgName" @click="dialogClick(item)">
          <span>{{item.orgName}}</span>
        </li>
      </ul>
    </el-scrollbar>
  </el-dialog>

</template>
<script setup>
import useStore from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { getQuestionConfig, saveQuestionConfig, removeQuestionSub } from '@/api/business/questions/questionconfig/QuestionConfig'
import { QuestionConfigBean, FORM_RULES, QuestionConfigSubBean } from '@/model/business/questions/questionconfig/QuestionConfigConstants'
import { getAllDeptList } from '@/api/business/questions/deptconfig/DeptConfig'

import '@/style/form.less'

const route = useRoute()
const router = useRouter()
const { menuStore } = useStore()
const formRef = ref()
const formData = ref({
  ...QuestionConfigBean,
  questions: [{
    ...QuestionConfigSubBean,
    showOrder: 1
  }]
})
const deptList = ref([])
const dialogFormVisible = ref(false)
const subSelectIndex = ref(0)
const searchOrg = ref('')

const addItem = () => {
  formData.value.questions.push({
    ...QuestionConfigSubBean,
    showOrder: maxOrder()
  })
}

const maxOrder = () => {
  let order = 1
  formData.value.questions.forEach(sub => {
    if (sub.showOrder > order) {
      order = sub.showOrder
    }
  })

  return order + 2
}

const selectDepts = computed(() => {
  return deptList.value.filter(item => item.orgName.indexOf(searchOrg.value) > -1)
})

const selectedOrg = computed(() => (item) => {
  return item.id === formData.value.questions[subSelectIndex.value].orgId ? 'selected-org' : ''
})

const handleClickOrg = (item, index) => {
  subSelectIndex.value = index
  dialogFormVisible.value = true
}

const dialogClick = (item) => {
  formData.value.questions[subSelectIndex.value].orgName = item.orgName
  formData.value.questions[subSelectIndex.value].orgId = item.id
  dialogFormVisible.value = false
}

const showContent = computed(() => {
  return '是否要删除?'
})

const delItem = (item, index) => {
  formData.value.questions.splice(index, 1)
  if (item.id) {
    removeQuestionSub(item.id)
  }
}

const onConfirmInitDept = () => {
  ElMessageBox.confirm('是否初始化部门信息？?')
    .then(() => {
      formData.value.questions.length = 0
      for (let i = 0; i < deptList.value.length; i++) {
        const dept = deptList.value[i]

        formData.value.questions.push({
          org: { label: dept.orgName, value: dept.id },
          orgId: dept.id,
          orgName: dept.orgName,
          question: '总体工作',
          showOrder: dept.showOrder
        })
      }
    })
    .catch(() => {
      // catch error
    })
}

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      saveQuestionConfig(formData.value).then(() => {
        loading.close()
        ElMessage.success('保存成功！')
        if (!formData.value.id) {
          handleClose()
        }
      }).catch(() => {
        loading.close()
        ElMessage.error('保存失败！')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const handleClose = () => {
  menuStore.closeCurrentPage(route, router)
}

onMounted(() => {
  const id = route.query.id

  if (id) {
    const loading = ElLoading.service({
      lock: true,
      text: '数据加载中……',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    getQuestionConfig(id).then(data => {
      formData.value = { ...data }
      loading.close()
    })
  }

  getAllDeptListData()
})

const getAllDeptListData = () => {
  getAllDeptList({}).then(data => {
    deptList.value = data.list
  }).catch(error => {
    ElMessage.warning(error.message || '数据查询异常')
  })
}

</script>
<style lang="scss">

.orgDialog{
  .el-dialog__header{
    display: none;
  }

  li{
    display: flex;
    padding: 8px;
    cursor: pointer;
  }

  li:hover {
      background-color: var(--el-fill-color-light);
  }

  .selected-org{
    color: var(--el-color-primary);
    font-weight: 550;
  }
}

.sub-order{
  text-align: center;
  line-height: 186px;
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-regular);
}
</style>
